package com.maoyu.cloud.spring.security;


import com.maoyu.cloud.login.entity.LoginUserEntity;
import com.maoyu.cloud.mybatis.entity.PtUserEntity;
import com.maoyu.cloud.user.service.LoginService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@Service("userDetailsService")
public class GdmtUserDetailsService implements UserDetailsService {
    private Logger logger = LogManager.getLogger(this.getClass());
    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private LoginService loginService;
    @Override
    public UserDetails loadUserByUsername(String username) throws
            UsernameNotFoundException {
        logger.info("userName:" + username);

        PtUserEntity ptUserEntity = loginService.queryUserInfoByName(username); //查询用户信息
        if (ptUserEntity == null) {
            throw new UsernameNotFoundException("username" + username);
        }
        logger.info("ptUserEntity:" + ptUserEntity);
//        String password = passwordEncoder.encode("123456");
        List<GrantedAuthority> collection = new ArrayList<>(); //用户权限
        //查询用户权限
        List<String> list = loginService.queryUserPermission(ptUserEntity.getUserUuid());
        for (String s : list) {
            collection.add(new SimpleGrantedAuthority("ROLE_" + s)); //添加权限
        }

        // 参数分别是：用户名，密码，用户权限

        LoginUserEntity user = new LoginUserEntity(username, ptUserEntity.getPassword(), ptUserEntity, collection); //用户信息

        return user;
    }

}
